import imConfig from '../config/index.js'
const BenderIM = {}
BenderIM.socketTask ={}

/**
 * im 连接是否连接了
 */
BenderIM.socketOpen = false



/**
 * @param {Object} userName
 * @param {Object} passWord
 * 连接websocket
 */
BenderIM.connectSocket = function(userName, passWord) {
	let loginSuccess = false
	if (!BenderIM.socketOpen) {
		BenderIM.socketTask = uni.connectSocket({
			url: imConfig.webscoketType + '://' + imConfig.websocketUrl + '?username=' + userName +
				'&password=' + passWord,
			complete: (res) => {
				console.log(JSON.stringify(res))
			},
			success: (res) => {
				loginSuccess = true
			}
		})
		/**
		 * @param {Object} res
		 * 监听 连接打开
		 */
		BenderIM.socketTask.onOpen(function(res) {
			BenderIM.socketOpen = true;
			// BenderIM.onSocketOpen(res)
		})
		/**
		 * @param {Object} res
		 * 监听 服务器返回的消息
		 */
		BenderIM.socketTask.onMessage(function(res) {
			if (res) {
				BenderIM.onSocketMessage(res)
			}
		})
		/**
		 * 监听 连接关闭事件
		 */
		BenderIM.socketTask.onClose(function(res) {
			BenderIM.onClose(res)
		})
		/**
		 * 监听 websocket 错误事件
		 */
		BenderIM.socketTask.onError(function(res) {
			BenderIM.onError(res)
		})

		return loginSuccess
	}
}
/**
 * 连接成功后的消息队列
 */
BenderIM.socketMsgQueue = []
/**
 * 连接开启后的操作
 */
BenderIM.onSocketOpen = function() {
	console.log('WebSocket连接已打开！');
	BenderIM.socketOpen = true;
	for (var i = 0; i < socketMsgQueue.length; i++) {
		BenderIM.sendSocketMessage(socketMsgQueue[i]);
	}
	BenderIM.socketMsgQueue = []
}

/**
 * @param {Object} msg消息
 * 发送wb 消息
 */
BenderIM.sendSocketMessage = function(msg) {
	console.log(JSON.stringify("发送的消息为"+JSON.stringify(msg)))
	if (BenderIM.socketOpen) {
		BenderIM.socketTask.send({
			data:JSON.stringify(msg),
			success:(res =>{
				console.log('发送消息成功')
			}),
			fail: () => {
				console.log('发送消息失败')
			}
		})
		
	} else {
		BenderIM.socketMsgQueue.push(msg);
	}
}
/**
 * @param {Object} msg
 * 监听WebSocket接受到服务器的消息事件
 * 
 */


import userMock from '../mock/user.js'
import chatMock from '../mock/chat.js'
import ImStorage from '../utils/ImStorage.js'
import ImEnum from '../enums/index.js'
import store from '../store/index.js'
BenderIM.onSocketMessage = function(res) {
	console.log('收到服务器内容：' + JSON.stringify(res));
	/**
	 * jim后台还不完善 先假处理 不想高了 等超哥后台好
	 */
	/**
	 * 登陆后提示加入群组成功
	 */
	let msg = JSON.parse(res.data)
	if (msg.code === 10011) {
		let user = ImStorage.getImStorageSync(ImEnum.ImStorageEnum.loginUserInfo)
		if (!user) {
			/**
			 * 设置登陆信息
			 */
			userMock.loginUserInfo.accountName = msg.user.userId
			userMock.loginUserInfo.id = msg.user.userId
			userMock.loginUserInfo.name = msg.user.nick
			userMock.loginUserInfo.nickName = msg.user.nick
			ImStorage.setImStorageSync(ImEnum.ImStorageEnum.loginUserInfo, userMock)
			/**
			 * 设置 聊天室信息 
			 */

			let chatroom = [{
				id: msg.group,
				name: 'JIM 朋友圈',
				nickName: 'JIM 朋友圈',
				avatar: 'https://cdn.quasar.dev/img/avatar.png',
				type: ImEnum.OtherEnum.USER_TYPE.GROUP,
				unReadCount: 1,
				lastChatTime: '10:22',
				lastChatContent: "你好啊，傻逼",
			}]
			store.dispatch(ImEnum.DataKeyEnum.CHAT_LIST, chatroom)

		}
	}else if(msg.command === 11){
		let time =new Date()
		let temp ={
			inChatUserId:'group-'+msg.data.groupId,
			msg:[{
					msgId:1,
					sender:msg.data.from,
					sendYear:time.getFullYear(),
					sendDay:time.getMonth()+'-' + time.getDate(),
					sendTime:time.getHours()+':'+time.getMinutes(),
					msgType:ImEnum.ImMsgTypeEnum.text,
					count:0,//视频或音频的长度
					msgStr:msg.data.content,
					url:''
				}]
		}
		store.dispatch(ImEnum.DataKeyEnum.addMsgDataKey,temp)
	}





}
/**
 * @param {Object} msg
 * 关闭im连接
 */
BenderIM.colseSocket = function() {
	uni.closeSocket(function(res) {
		console.log('关闭连接中：' + JSON.stringify(res));
	});
}
/**
 * @param {Object} res
 * 连接关闭后调用
 */
BenderIM.onClose = function(res) {
	BenderIM.socketOpen = false
	console.log('关闭连接成功：' + JSON.stringify(res));
}
/**
 * @param {Object} res
 * 连接关闭后调用
 */
BenderIM.onError = function(res) {
	console.log('连接错误：' + JSON.stringify(res));
}



export default BenderIM
